package cn.ywyself.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * 文本内容服务, 储存文本到文件
 */
@Service
public class TextServer {

    private final Logger logger = LoggerFactory.getLogger(TextServer.class);

    private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    /**
     * 追加式写入
     */
    public boolean append(String text) {
        logger.debug("接收到数据[{}]", text);
        BufferedWriter bw = null;
        String fileName = "/data/text.log";
        try {
            File f = new File(fileName);
            if (!f.exists()) {
                logger.info("文件不存在, 正在创建新文件");
                bw = new BufferedWriter(new FileWriter(f));
            } else {
                bw = new BufferedWriter(new FileWriter(f, true));
            }
            LocalDateTime now = LocalDateTime.now();
            String nowText = now.format(dtf);
            bw.write(nowText + " " + text);
            bw.newLine();
        } catch (IOException e) {
            logger.error("\nexception : {}\nerrorTrack : {}", String.valueOf(e), errorTrack(e));
            logger.error("数据写入失败");
            return false;
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException ignored) {
            }
        }
        logger.info("数据写入成功");
        return true;

    }

    /**
     * 输出异常信息
     */
    private static String errorTrack(Exception e) {
        StringBuilder sb = new StringBuilder();
        if (e != null) {
            for (StackTraceElement element : e.getStackTrace()) {
                sb.append("\r\n\t").append(element);
            }
        }
        return sb.length() == 0 ? null : sb.toString();
    }
}